package com.am.server.api.system.permission.service.impl;

import com.am.server.api.system.permission.config.model.Menu;
import com.am.server.api.system.permission.dao.cache.MenuCacheDao;
import com.am.server.api.system.permission.model.dto.MenuTreeDto;
import com.am.server.api.system.permission.service.PermissionService;
import com.am.server.api.system.permission.service.SystemPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author 阮雪峰
 */
@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService {

    private final SystemPermissionService systemPermissionService;
    private final MenuCacheDao menuCacheDao;

    public PermissionServiceImpl(SystemPermissionService systemPermissionService, MenuCacheDao menuCacheDao) {
        this.systemPermissionService = systemPermissionService;
        this.menuCacheDao = menuCacheDao;
    }

    @Override
    public List<MenuTreeDto> tree() {
        return Optional.of(systemPermissionService.getAllTree())
                .map(this::mapToTreeVo)
                .orElse(Collections.emptyList());
    }

    private List<MenuTreeDto> mapToTreeVo(List<Menu> list) {
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        return list.stream().map(item -> new MenuTreeDto(item.getId(), item.getMeta().getTitle(), item.getPath(), mapToTreeVo(item.getChildren()))).toList();
    }

    @Override
    public List<Menu> findByIds(Collection<String> menuIdList) {
        return menuCacheDao.findByIds(new ArrayList<>(menuIdList));
    }

    @Override
    public Optional<Menu> findById(String menuId) {
        return menuCacheDao.findById(menuId);
    }

    @Override
    public List<MenuTreeDto> menuTree() {
        return Optional.of(systemPermissionService.getMenuTree())
                .map(this::mapToTreeVo)
                .orElse(Collections.emptyList());
    }
}
